<template>
  <ContentContainer
    :show-pagination="false"
    :show-footer="false"
    :refresh="false"
    inner>
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      layout="vertical"
      class="overflow-hidden"
      scroll-to-first-error>
      <div class="weight-label">首页缓存</div>
      <span class="sub-label">
        指定首页内容的缓存过期时间，提升首页访问性能
      </span>
      <a-form-item
        field="cache_config.index_cache_enable"
        hide-label
        hide-asterisk
        asterisk-position="end"
        class="!mb-0"
        required>
        <a-checkbox
          v-model="form.cache_config.index_cache_enable"
          size="large"
          @change="handleCacheSave"
          >启用</a-checkbox
        >
      </a-form-item>
      <a-form-item
        v-if="form.cache_config.index_cache_enable"
        field="cache_config.index_cache_time"
        label="过期时间"
        hide-asterisk
        asterisk-position="end"
        required>
        <section class="flex flex-col">
          <section class="w-100 append-select">
            <a-input-number
              v-model="form.cache_config.index_cache_time!"
              :precision="0"
              :min="1"
              :max="form.index_cache_unit === 'd' ? 365 : 99999"
              hide-button
              :default-value="10"
              placeholder="请输入"
              class="expired-time-input"
              @change="handleCacheSave">
              <template #append>
                <a-select
                  v-model="form.index_cache_unit"
                  class="!w-78px"
                  :options="cacheTimeOptions"
                  @change="handleCacheSave">
                </a-select>
              </template>
            </a-input-number>
          </section>
        </section>
      </a-form-item>
      <a-divider type="dashed" />
      <div class="weight-label">缓存配置</div>
      <div class="sub-label mb-6">
        指定资源内容的缓存过期时间，有效提升资源的命中率，提升访问性能，减少回源
      </div>
      <a-form-item class="!w-200">
        <cache-rule-table
          ref="cacheRuleTableRef"
          v-model:list="form.cache_config.suffix_cache_rule"
          @refresh="request"
          @save="handleCacheSave">
        </cache-rule-table>
      </a-form-item>

      <a-form-item>
        <section class="flex flex-col">
          <a-checkbox
            v-model="form.cache_config.ignore_query_string"
            class="!leading-22px"
            @change="handleCacheSave"
            >忽略查询字符串</a-checkbox
          >
          <span class="sub-label">
            忽略查询字符串，向所有用户提供相同的资源。示例：example.com/index.jpg?ignore=this-query-string
          </span>
        </section>
      </a-form-item>
      <a-form-item>
        <section class="flex flex-col">
          <span>浏览器缓存 TTL</span>
          <span class="sub-label">
            用于配置资源在浏览器中的缓存时长，可降低回源率
          </span>
          <a-radio-group
            v-model="form.cache_config.browser_cache_enable"
            class="my-2"
            @change="handleCacheSave">
            <a-radio :value="false">遵循源站</a-radio>
            <a-radio :value="true">自定义</a-radio>
          </a-radio-group>
          <a-form-item
            v-if="form.cache_config.browser_cache_enable"
            field="cache_config.browser_cache_time"
            hide-asterisk
            hide-label
            class="!w-100 flex items-center append-select"
            required>
            <a-input-number
              v-model="form.cache_config.browser_cache_time!"
              :min="1"
              :max="form.browser_cache_unit === 'd' ? 365 : 99999"
              :precision="0"
              :default-value="60"
              hide-button
              placeholder="请输入"
              @change="handleCacheSave">
            </a-input-number>
            <a-select
              v-model="form.browser_cache_unit"
              :options="cacheTimeOptions"
              class="time-unit-select"
              @change="handleCacheSave">
            </a-select>
          </a-form-item>
        </section>
      </a-form-item>

      <a-divider type="dashed" class="!mt-0" />
      <div class="weight-label">压缩配置</div>
      <div class="sub-label mb-6">
        节点对资源进行压缩 ，减小传输文件大小，提升请求资源的加载速度。
      </div>
      <a-form-item label="Brotli 压缩" class="label-col-no-margin">
        <a-checkbox-group v-model="form.brotli" @change="handleSave">
          <a-checkbox
            v-for="item in compressOptions"
            :key="item.value"
            :value="item.value"
            >{{ item.label }}</a-checkbox
          >
        </a-checkbox-group>
      </a-form-item>
      <a-form-item label="Gzip 压缩" class="label-col-no-margin">
        <a-checkbox-group v-model="form.gzip" @change="handleSave">
          <a-checkbox
            v-for="item in compressOptions"
            :key="item.value"
            :value="item.value"
            >{{ item.label }}</a-checkbox
          >
        </a-checkbox-group>
      </a-form-item>
    </a-form>
    <div class="flex flex-col sub-label mt-6">
      <span>注意：</span>
      <span> 1.请求压缩头与压缩类型一致时，压缩才会生效；</span>
      <span> 2.同时开启 Gzip 压缩与 Brotli 压缩优先响应 Brotli 压缩；</span>
      <span>
        3.若源站文件自身有 MD5 值校验机制，开启压缩可能会影响站点的功能；</span
      >
    </div>
  </ContentContainer>
</template>
<script lang="ts" setup>
import {
  getApiSiteCacheConfigApi,
  getApiSiteCompressionApi,
  updateApiSiteCacheConfigApi,
  updateApiSiteCompressionApi
} from '@/apis/modules/site/site'
import { cloneDeep } from 'lodash-es'
import CacheRuleTable from '../../components/CacheRuleTable'
const route = useRoute()
const formRef = ref()
const cacheRuleTableRef = ref<InstanceType<typeof CacheRuleTable>>()
const form = reactive({
  index_cache_unit: A_CACHE_TIME.HOUR,
  browser_cache_unit: A_CACHE_TIME.SECOND,
  brotli: [],
  gzip: [],
  cache_config: {
    browser_cache_enable: false,
    browser_cache_time: 60,
    ignore_query_string: false,
    index_cache_enable: false,
    index_cache_time: 10,
    suffix_cache_rule: [{ suffix: '', cache_time: '', cache_unit: '' }] as any[]
  }
})

const rules = {
  'cache_config.browser_cache_time': [
    { required: true, message: '请输入浏览器缓存时间' }
  ],
  'cache_config.index_cache_time': [
    { required: true, message: '请输入过期时间' }
  ],
  region_id: [{ required: true, message: '请选择区域' }],
  protocol: [{ required: true, message: '请选择回源协议' }],
  host: [
    { required: true, message: '请输入自定义域名' },
    { validator: validateDomain }
  ]
}
const id = computed(() => route.params.id as string)
//缓存配置
const { request } = useRequest(getApiSiteCacheConfigApi, {
  auto: true,
  params: { id: id.value },
  success: (res) => {
    Object.assign(form, res)
    if (!res!.cache_config!.browser_cache_time) {
      form.cache_config.browser_cache_time = 60
      form.browser_cache_unit = A_CACHE_TIME.SECOND
    } else {
      const browserCacheData = separateNumberAndLetter(
        res!.cache_config!.browser_cache_time!
      )
      form.cache_config.browser_cache_time = +browserCacheData.value as any
      form.browser_cache_unit = browserCacheData.unit! as any
    }
    if (!res!.cache_config!.index_cache_time!) {
      form.cache_config.index_cache_time = 10
      form.index_cache_unit = A_CACHE_TIME.MINUTE
    } else {
      const indexCacheData = separateNumberAndLetter(
        res!.cache_config!.index_cache_time!
      )
      form.cache_config.index_cache_time = +indexCacheData.value as any
      form.index_cache_unit = indexCacheData.unit! as any
    }
    form.cache_config.suffix_cache_rule.forEach((item) => {
      if (item.suffix.length) {
        item.suffix = item.suffix.join(',')
        const cacheData = separateNumberAndLetter(item.cache_time)
        item.cache_time = cacheData.value
        item.cache_unit = cacheData.unit
      } else {
        item.cache_time = '60'
        item.suffix = ''
        item.cache_unit = 's'
      }
    })
  }
})
//缓存配置保存
const handleCacheSave = async () => {
  const err = await formRef.value?.validate()
  if (err) return
  const data = cloneDeep({
    ...form,
    id: id.value
  })
  if (!form.cache_config.browser_cache_enable) {
    data.cache_config.browser_cache_time = undefined
  } else {
    data.cache_config.browser_cache_time = ((data.cache_config
      .browser_cache_time || 60) + data.browser_cache_unit) as any
  }
  if (!form.cache_config.index_cache_enable) {
    data.cache_config.index_cache_time = undefined
  } else {
    data.cache_config.index_cache_time = ((data.cache_config.index_cache_time ||
      10) + data.index_cache_unit) as any
  }
  data.cache_config.suffix_cache_rule.forEach((item) => {
    item.suffix = item.suffix?.split(',') ?? []
    item.cache_time = item.cache_time + item.cache_unit
    delete item.cache_unit
  })
  try {
    await updateApiSiteCacheConfigApi({ ...data })
    ToastUtils.success('保存成功')
  } catch {
    request()
  }
}
//压缩配置
const { request: compressRequest } = useRequest(getApiSiteCompressionApi, {
  auto: true,
  params: { id: id.value },
  success: (res) => {
    Object.assign(form, res)
  }
})
const handleSave = async () => {
  const err = await formRef.value?.validate()
  if (err) return
  const data = cloneDeep({
    site_compression: {
      brotli: form.brotli,
      gzip: form.gzip
    },
    id: id.value
  })
  await updateApiSiteCompressionApi({ ...data })
  ToastUtils.success('保存成功')
}
watchEffect(() => {
  request({ id: id.value })
  compressRequest({ id: id.value })
})
</script>

<style lang="less" scoped>
.expired-time-input {
  :deep(.arco-input-wrapper) {
    border-top-left-radius: 4px !important;
    border-bottom-left-radius: 4px !important;
  }
  :deep(.arco-input-append) {
    border: none;
  }
}
:deep(.arco-select-view-single) {
  .arco-select-view-suffix {
    padding-left: 4px;
  }
}
.weight-label {
  @apply text-sm/22px font-700;
}
.sub-label {
  @apply text-xs/5 text-5;
}
.label-col-no-margin {
  :deep(.arco-form-item-label-col) {
    @apply mb-0;
  }
}
</style>
